import 'package:im_module/common/GroupCommonType.dart';
import 'package:im_module/common/connect_state.dart';
import 'package:im_module/common/message_cache_key.dart';
import 'package:im_module/provider/im_provider.dart';
import 'package:im_module/pwd_info.dart';
import 'package:provider/provider.dart';
import 'package:tencent_im_sdk_plugin/enum/V2TimAdvancedMsgListener.dart';
import 'package:tencent_im_sdk_plugin/enum/V2TimConversationListener.dart';
import 'package:tencent_im_sdk_plugin/enum/V2TimFriendshipListener.dart';
import 'package:tencent_im_sdk_plugin/enum/V2TimGroupListener.dart';
import 'package:tencent_im_sdk_plugin/enum/V2TimSDKListener.dart';
import 'package:tencent_im_sdk_plugin/enum/log_level.dart';
import 'package:tencent_im_sdk_plugin/manager/v2_tim_manager.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_callback.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_conversation.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_friend_application.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_friend_check_result.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_friend_info.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_friend_info_result.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_friend_operation_result.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_group_info.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_group_info_result.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_group_member_full_info.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_group_member_info.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_group_member_info_result.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_group_member_operation_result.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_message.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_message_receipt.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_user_full_info.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_value_callback.dart';
import 'package:tencent_im_sdk_plugin/tencent_im_sdk_plugin.dart';

import '../global_context.dart';

class ImChatManager {
  factory ImChatManager() => _getInstance();

  static ImChatManager? _instance;

  ImChatManager._internal() {
    // 初始化
  }

  late String currentUserid = '';
  late String currentUserHead = '';

  static ImChatManager _getInstance() {
    if (_instance == null) {
      _instance = new ImChatManager._internal();
    }
    return _instance!;
  }

  ///的用户信息
  List<UserInfoConfig> getData() {
    List<UserInfoConfig> _data = List.empty(growable: true);
    _data.add(UserInfoConfig(
        "1",
        "eJwtzM0KgkAYheF7mW0h3-yVCq2aFllBUotcJjPZhybDzCRFdO*ZujzPgfdDzvtT1BlHUsIiIPNhozZtwBsOTCf0ur5ai5qkVABIRmOWjI95WXSmdyklA4BRAz7*tmAUxJJSOVWw6psbXfDinZmyaY87uw1Pd-GHOk5mRt1zxfKsE46rxvN1tSLfHxOCL6g_",
        "这个是用户1",
        "https://sf1-ttcdn-tos.pstatp.com/img/user-avatar/55024cc237dfc23b1c88540e18f707e5~300x300.image"));

    _data.add(UserInfoConfig(
        "2",
        "eJwtzMsKwjAQheF3ma1SJkNS04ILQV25M4rb1sR0KC21N4riu1tNl*c78L-BnM7R6FpIgSKE9X*zdXXPDw68YGfLrGnYQiokoiKhKQmPmxpu3exKKULEoD1XP4tJoNxQopcK*7m5umppnsXF3gatdr6sTXIfDn6fx2OmxYvUsXd5Yae86rbw*QIDci-W",
        "这个是用户2",
        "https://sf6-ttcdn-tos.pstatp.com/img/user-avatar/97aec65b1390d7500163f818edd2fe07~300x300.image"));

    _data.add(UserInfoConfig(
        "3",
        "eJyrVgrxCdYrSy1SslIy0jNQ0gHzM1NS80oy0zLBwsZQweKU7MSCgswUJStDEwMDUyNDCyNLiExqRUFmUSpQ3NTU1MjAwAAiWpKZCxIzMzI0NgbJQE3JTAeaGVEWUOKXUhWe7p7iHKOfXVCcnRZQVRXkZ2JZXOle4GTqnFaYFemdmZfta2Zgq1QLAFpdMMg_",
        "这个是用户3",
        "https://sf3-ttcdn-tos.pstatp.com/img/user-avatar/b29c181a7f304eee29eb2a03159d97c9~300x300.image"));

    _data.add(UserInfoConfig(
        "4",
        "eJyrVgrxCdYrSy1SslIy0jNQ0gHzM1NS80oy0zLBwiZQweKU7MSCgswUJStDEwMDUyNDCyNLiExqRUFmUSpQ3NTU1MjAwAAiWpKZCxIzMzI0NjU2NjeBmpKZDjQzNajC2T*0Qtu4IsPQtbDcOSCg0rEyx8kvuyQprLTMUzvRIjkyqMLFIzPd11apFgAY1jAq",
        "这个是用户4",
        "https://sf6-ttcdn-tos.pstatp.com/img/user-avatar/553525665fce924274a5fea3e42d289b~300x300.image"));

    _data.add(UserInfoConfig(
        "5",
        "eJyrVgrxCdYrSy1SslIy0jNQ0gHzM1NS80oy0zLBwqZQweKU7MSCgswUJStDEwMDUyNDCyNLiExqRUFmUSpQ3NTU1MjAwAAiWpKZCxIzMzI0NTewtDCGmpKZDjQzpyLM3dOz1M2lzLUs3Nw-IiUwp8g1PSs-NzswNDg8wtkkJMvYz9Is17c01FapFgAcbS-x",
        "这个是用户5",
        "https://sf3-ttcdn-tos.pstatp.com/img/user-avatar/f7a133a1ca0cbff844cd1329c5e36ca8~300x300.image"));
    return _data;
  }

  /// 初始化聊天
  initSdk(mContext, int appId, UserInfoConfig userInfoConfig) {
    V2TIMManager _timManager = TencentImSDKPlugin.v2TIMManager;
    _timManager
        .initSDK(
      sdkAppID: appId,
      loglevel: LogLevel.V2TIM_LOG_DEBUG,
      listener: listener,
    )
        .then((value) {
      //初始化成功后 在调用登录接口
      if (value.code == 0) {
        //初始化消息监听
        initMessageListener();

        loginIm(userInfoConfig);
      }
    });
  }

  ///登录聊天
  void loginIm(UserInfoConfig userInfoConfig) {
    V2TIMManager _timManager = TencentImSDKPlugin.v2TIMManager;
    _timManager.getVersion().then((value) => print("当前版本号：${value.data}"));

    //登录
    _timManager
        .login(userID: userInfoConfig.userId, userSig: userInfoConfig.userToken)
        .then(
      (value) {
        if (value.code == 0) {
          //登录成功  监听好友连接
          print("登录成功");

          //设置当前的用户id
          currentUserid = userInfoConfig.userId;
          currentUserHead = userInfoConfig.faceUrl;

          Provider.of<ImProvider>(GlobalContext.getContext(), listen: false)
              .setState(ImConnectState.loginSuccess);

          //初始化朋友监听
          initFriendListener();

          //群聊监听
          initGroupListener();

          //获取最近的会话列表
          getConversationList(0);

          //获取未读消息数量
          getUnReadMessageCount();

          //初始化回话列表监听
          initConversationChanged();

          //初始化用户信息
          initUserInfo(userInfoConfig.userId, userInfoConfig.niceName,
              userInfoConfig.faceUrl);
        }
      },
    ).onError((error, stackTrace) {});
  }

  ///获取当前登录的用户id
  String getUserId() {
    return currentUserid;
  }

  ///获取登录状态  1已登录 2登录中 3无登录
  Future<int?> getLoginStatus() async {
    V2TimValueCallback<int> callback =
        await TencentImSDKPlugin.v2TIMManager.getLoginStatus();

    if (callback.code == 0) {
      return Future.value(callback.data);
    } else {
      return Future.value(-1);
    }
  }

  ///退出登录 不能多次调用 回调完后，才继续调用
  Future<bool> logout() async {
    V2TimCallback callback = await TencentImSDKPlugin.v2TIMManager.logout();
    if (callback.code == 0) {
      Provider.of<ImProvider>(GlobalContext.getContext(), listen: false)
          .clearValue();
    }
    return Future.value(callback.code == 0);
  }

  ///初始化用户信息
  void initUserInfo(String userId, String niceName, String face) async {
    /*V2TimValueCallback<List<V2TimUserFullInfo>> _resultUserInfo =
        await TencentImSDKPlugin.v2TIMManager
            .getUsersInfo(userIDList: [userId]);

    //请求成功
    if (_resultUserInfo.code == 0) {
      if (_resultUserInfo.data == null || _resultUserInfo.data!.isEmpty) {
        setUserInfo(niceName, face);
        return;
      }
      V2TimUserFullInfo _userInfo = _resultUserInfo.data!.first;

      //判断是否有设置过头像和用户名
      if (_userInfo.nickName == null || _userInfo.faceUrl == null) {
        setUserInfo(niceName, face);
      }
    } else {
      setUserInfo(niceName, face);
    }*/
    setUserInfo(niceName, face);
  }

  void setUserInfo(String userName, String userFace) {
    if (userFace == null ||
        userName == null ||
        userName == "" ||
        userName == "") {
      return;
    }
    TencentImSDKPlugin.v2TIMManager
        .setSelfInfo(
          userFullInfo:
              V2TimUserFullInfo(nickName: userName, faceUrl: userFace),
        )
        .then((value) => {
              if (value.code == 0) {print("设置用户信息： ${value.toJson()}")},
            });
  }

  ///获取好友列表
  void getFriendList() async {
    V2TimValueCallback<List<V2TimFriendInfo>> friends = await TencentImSDKPlugin
        .v2TIMManager
        .getFriendshipManager()
        .getFriendList();

    if (friends.code == 0) {
      //过滤当前登录用户
      friends.data?.removeWhere((element) => element.userID == getUserId());

      Provider.of<ImProvider>(GlobalContext.getContext(), listen: false)
          .setFriendList(friends.data);
    }
  }

  ///获取会话列表
  void getConversationList(int nextSeq) {
    TencentImSDKPlugin.v2TIMManager
        .getConversationManager()
        .getConversationList(nextSeq: "$nextSeq", count: 100)
        .then(
          (value) => {
            if (value.code == 0)
              {
                Provider.of<ImProvider>(GlobalContext.getContext(),
                        listen: false)
                    .setConversation(nextSeq, value.data!.conversationList)
              },
          },
        );
  }

  ///添加好友 addType 1添加好友 需要同意、2添加好友不需要同意
  Future<bool> addFriend(userID) async {
    V2TimValueCallback<V2TimFriendOperationResult> _result =
        await TencentImSDKPlugin.v2TIMManager
            .getFriendshipManager()
            .addFriend(userID: userID, addType: 1);

    return Future.value(_result.code == 0);
  }

  ///重新发送消息
  void reSendMessage(String key, String msgID) async {
    V2TimValueCallback<V2TimMessage> message = await TencentImSDKPlugin
        .v2TIMManager
        .getMessageManager()
        .reSendMessage(msgID: msgID);

    if (message.code == 0) {
      Provider.of<ImProvider>(GlobalContext.getContext(), listen: false)
          .addMessage(key, message.data!);
    }
  }

  ///发送消息 1发送了私聊消息  2发送群聊消息
  void sendMessage(int type, key, id, value) async {
    V2TimValueCallback<V2TimMessage> message;

    if (type == 1) {
      message = await TencentImSDKPlugin.v2TIMManager
          .getMessageManager()
          .sendTextMessage(text: value, receiver: id, groupID: "");
    } else {
      message = await TencentImSDKPlugin.v2TIMManager
          .getMessageManager()
          .sendTextMessage(text: value, receiver: "", groupID: id);
    }
    /*if (type == 1) {
      message = await TencentImSDKPlugin.v2TIMManager
          .sendC2CTextMessage(text: value, userID: id);
    } else {
      message = await TencentImSDKPlugin.v2TIMManager
          .sendGroupTextMessage(groupID: id, text: value);
    }*/

    print("发送了信息key=:$key    ${message.code}   ${message.data?.toJson()}");

    //if (message.code == 0) {
    //状态码 10007  20009 message.data会为null
    if (message.data != null) {
      Provider.of<ImProvider>(GlobalContext.getContext(), listen: false)
          .addMessage(key, message.data!);
    }
    //}
  }

  ///发送图片消息
  ///@key 私聊缓存 群聊缓存
  ///@type 1私聊 2群聊
  ///@id 聊天对象的id 或者是群聊id
  void sendImageMessage(key, int type, String id, path) {
    print("发送图片:$path");
    TencentImSDKPlugin.v2TIMManager
        .getMessageManager()
        .sendImageMessage(
            imagePath: path, receiver: type == 1 ? id : "", groupID: type == 2 ? id : "")
        .then((value) {
      print("发送图片:${value.code}");
      if (value.code == 0) {
        Provider.of<ImProvider>(GlobalContext.getContext(), listen: false)
            .addMessage(key, value.data!);
      }
    });
  }

  ///发送地理位置消息
  void sendLocationMessage(key, int type, String desc, double longitude,
      double latitude, String id) {
    TencentImSDKPlugin.v2TIMManager
        .getMessageManager()
        .sendLocationMessage(
            desc: desc,
            longitude: longitude,
            latitude: latitude,
            receiver: type == 1 ? id : "",
            groupID: type == 2 ? id : "")
        .then((value) => {
              print("发送地理位置消息:$value"),
              Provider.of<ImProvider>(GlobalContext.getContext(), listen: false)
                  .addMessage(key, value.data!),
            });
  }

  ///获取历史消息
  ///@key 私聊缓存 群聊缓存
  ///@_type 1 单聊消息  2群消息
  ///@userID  聊天对象的id
  ///@lastMsgID 消息id
  void getHistoryMessageList(
      String key, int _type, String userID, lastMsgID) async {
    V2TimValueCallback<List<V2TimMessage>> _message;

    if (_type == 1) {
      _message = await TencentImSDKPlugin.v2TIMManager.v2TIMMessageManager
          .getC2CHistoryMessageList(
              userID: userID, count: 20, lastMsgID: lastMsgID);
    } else {
      _message = await TencentImSDKPlugin.v2TIMManager.v2TIMMessageManager
          .getGroupHistoryMessageList(
              groupID: userID, count: 20, lastMsgID: lastMsgID);
    }
    //添加消息
    if (_message.code == 0) {
      if (_message.data == null || _message.data!.isEmpty) {
        return;
      }
      Provider.of<ImProvider>(GlobalContext.getContext(), listen: false)
          .addMessages(key, _message.data);
    }
  }

  ///设置单聊消息已读
  /// _type 1 单聊消息  2群消息
  void markC2CMessageAsRead(int _type, String id) {
    if (_type == 1) {
      TencentImSDKPlugin.v2TIMManager.v2TIMMessageManager
          .markC2CMessageAsRead(userID: id)
          .then((value) => print("单聊消息已读:${value.code}"));
    } else {
      TencentImSDKPlugin.v2TIMManager.v2TIMMessageManager
          .markGroupMessageAsRead(groupID: id)
          .then((value) => print("群聊消息已读:${value.code}"));
    }
  }

  ///获取未读消息数量
  getUnReadMessageCount() {
    TencentImSDKPlugin.v2TIMManager
        .getConversationManager()
        .getTotalUnreadMessageCount()
        .then((value) {
      if (value.code == 0) {
        Provider.of<ImProvider>(GlobalContext.getContext(), listen: false)
            .setMessageUnReadCount(value.data!);
      }
    });
  }

  ///回话数量变化通知
  initConversationChanged() {
    TencentImSDKPlugin.v2TIMManager
        .getConversationManager()
        .setConversationListener(
          listener: V2TimConversationListener(
            onSyncServerStart: () {
              //同步服务器会话开始，SDK 会在登录成功或者断网重连后自动同步服务器会话，您可以监听这个事件做一些 UI 进度展示操作。
            },
            onSyncServerFinish: () {
              //同步服务器会话完成，如果会话有变更，会通过 onNewConversation | onConversationChanged 回调告知客户
            },
            onConversationChanged: (List<V2TimConversation> conversationList) {
              //某些会话的关键信息发生变化（未读计数发生变化、最后一条消息被更新等等），可以根据会话的 lastMessage -> timestamp 重新对会话列表做排序

              //print("最后一条消息->${conversationList[0].lastMessage?.toJson()}");

              //重新获取未读总数
              getUnReadMessageCount();

              //设置新的会话
              Provider.of<ImProvider>(GlobalContext.getContext(), listen: false)
                  .setConversation(0, conversationList);
            },
            onNewConversation: (List<V2TimConversation> conversationList) {
              //有新的会话（比如收到一个新同事发来的单聊消息、或者被拉入了一个新的群组中），可以根据会话的 lastMessage -> timestamp 重新对会话列表做排序
              print("onNewChanged:${conversationList.first.toJson()}");

              //重新获取未读总数
              getUnReadMessageCount();

              //设置新的会话
              Provider.of<ImProvider>(GlobalContext.getContext(), listen: false)
                  .setConversation(0, conversationList);
            },
          ),
        );
  }

  ///连接监听
  V2TimSDKListener listener = new V2TimSDKListener(
    onConnecting: () => {
      //正在连接中
      print("正在连接中"),
      Provider.of<ImProvider>(GlobalContext.getContext(), listen: false)
          .setState(ImConnectState.connectIng)
    },
    onConnectFailed: (int code, String error) {
      //连接腾讯云服务器失败
      print("失败");
      Provider.of<ImProvider>(GlobalContext.getContext(), listen: false)
          .setState(ImConnectState.connectFailed);
    },
    onConnectSuccess: () => {
      //已经成功连接到腾讯云服务器
      print("成功"),
      Provider.of<ImProvider>(GlobalContext.getContext(), listen: false)
          .setState(ImConnectState.connectSuccess),
    },
    onKickedOffline: () => {
      //当前用户被踢下线
      print("被踢下线"),
      Provider.of<ImProvider>(GlobalContext.getContext(), listen: false)
          .setState(ImConnectState.kickedOffline),
    },
  );

  ///好友好友申请列表
  void getUnFriendReadCount() async {
    var _result = await TencentImSDKPlugin.v2TIMManager
        .getFriendshipManager()
        .getFriendApplicationList();
    if (_result.code == 0) {
      //好友申请未读数量
      Provider.of<ImProvider>(GlobalContext.getContext(), listen: false)
          .setUnFriendReadCount(_result.data?.unreadCount);

      //好友申请列表
      Provider.of<ImProvider>(GlobalContext.getContext(), listen: false)
          .setApplyFriends(_result.data?.friendApplicationList);
    }
  }

  ///同意好友申请
  ///responseType 0同意加好友（建立单向好友）  1同意加好友并加对方为好友（建立双向好友）
  Future<bool> acceptFriend(V2TimFriendApplication application) async {
    V2TimValueCallback<V2TimFriendOperationResult> res =
        await TencentImSDKPlugin.v2TIMManager
            .getFriendshipManager()
            .acceptFriendApplication(
              responseType: 1,
              type: application.type,
              userID: application.userID,
            );
    if (res.code == 0) {
      print("添加好友成功");
      //同意好友 刷新好友数据
      getFriendList();

      //获取重新获取申请列表
      getUnFriendReadCount();

      return Future.value(true);

      //insertC2cMessage("你们现在互为好友,现在可以开始聊天聊", application.userID, "");
    } else {
      return Future.value(false);
    }
  }

  ///单聊消息中插入一条提示语句
  void insertC2cMessage(String value, userID, senderId) {
    TencentImSDKPlugin.v2TIMManager.v2TIMMessageManager
        .insertC2CMessageToLocalStorage(
            data: value, userID: userID, sender: senderId)
        .then((value) => {
              if (value.code == 0)
                {
                  //发送成功
                  Provider.of<ImProvider>(GlobalContext.getContext(),
                          listen: false)
                      .addMessage(
                          MessageCacheKey.getC2cKey(userID), value.data!),
                },
            });
  }

  ///检测是否是好友
  ///checkType 1单向好友 2互为好友
  ///return -1 表示不在服务器中、0不是好友、1对方在我的好友列表中  2表示我在对方的好友列表中  3表示互为好友
  Future<int> checkFriend(String userId) async {
    V2TimValueCallback<List<V2TimFriendCheckResult>> _future =
        await TencentImSDKPlugin.v2TIMManager
            .getFriendshipManager()
            .checkFriend(userIDList: [userId], checkType: 2);

    if (_future.code == 0) {
      int? resultType = _future.data?[0].resultType;
      return Future.value(resultType);
    } else {
      return Future.value(-1);
    }
  }

  ///获取好友信息
  Future<V2TimFriendInfoResult?> getFriendsInfo(String userId) async {
    V2TimValueCallback<List<V2TimFriendInfoResult>> _result =
        await TencentImSDKPlugin.v2TIMManager
            .getFriendshipManager()
            .getFriendsInfo(userIDList: [userId]);

    if (_result.code == 0) {
      if (_result.data == null || _result.data!.isEmpty) {
        return Future.value(null);
      }
      V2TimFriendInfoResult? friendInfo = _result.data!.first;
      return Future.value(friendInfo);
    } else {
      return Future.value(null);
    }
  }

  ///删除好友
  Future<bool> deleteFromFriendList(String userId) async {
    V2TimValueCallback<List<V2TimFriendOperationResult>> _result =
        await TencentImSDKPlugin.v2TIMManager.v2TIMFriendshipManager
            .deleteFromFriendList(userIDList: [userId], deleteType: 2);

    return Future.value(_result.code == 0);
  }

  ///初始化消息监听
  void initMessageListener() {
    V2TimAdvancedMsgListener advancedMsgListener = new V2TimAdvancedMsgListener(
      onRecvNewMessage: (V2TimMessage msg) {
        print("onRecvNewMessage->${msg.toJson()}");

        String key;
        if (msg.groupID == null) {
          key = MessageCacheKey.getC2cKey("${msg.userID}");
        } else {
          key = MessageCacheKey.getGroupKey("${msg.groupID}");
        }
        Provider.of<ImProvider>(GlobalContext.getContext(), listen: false)
            .addMessage(key, msg);
      },
      onRecvC2CReadReceipt: (List<V2TimMessageReceipt> receiptList) {
        //设置消息已读
        receiptList.forEach((element) {
          Provider.of<ImProvider>(GlobalContext.getContext(), listen: false)
              .updateC2CMessageByUserId(element.userID);
        });

        //重新获取消息
        getUnReadMessageCount();
      },
      onSendMessageProgress: (V2TimMessage message, int progress) {
        print("onSendMessageProgress->$progress    ${message.toJson()}");
        String key;
        if (message.groupID == null) {
          key = MessageCacheKey.getC2cKey("${message.userID}");
        } else {
          key = MessageCacheKey.getGroupKey("${message.groupID}");
        }
        //
        Provider.of<ImProvider>(GlobalContext.getContext(), listen: false)
            .addOneMessageIfNotExits(key, message);
      },
    );
    //移除消息监听
    TencentImSDKPlugin.v2TIMManager
        .getMessageManager()
        .removeAdvancedMsgListener();

    //添加消息监听
    TencentImSDKPlugin.v2TIMManager.getMessageManager().addAdvancedMsgListener(
          listener: advancedMsgListener,
        );
  }

  ///设置好友申请已读
  void setFriendApplicationRead() {
    TencentImSDKPlugin.v2TIMManager.v2TIMFriendshipManager
        .setFriendApplicationRead()
        .then((value) => print("好友申请已读"));
  }

  ///初始化好友关系监听
  void initFriendListener() {
    TencentImSDKPlugin.v2TIMManager.getFriendshipManager().setFriendListener(
          listener: new V2TimFriendshipListener(
            ///好友申请新增通知，两种情况会收到这个回调：
            ///
            /// 自己申请加别人好友
            /// 别人申请加自己好友
            onFriendApplicationListAdded: (applicationList) {
              //获取下未读好友申请数量
              print("好友申请新增通知");
              getUnFriendReadCount();
            },

            ///好友申请删除通知，四种情况会收到这个回调
            ///
            /// 调用 deleteFriendApplication 主动删除好友申请
            /// 调用 refuseFriendApplication 拒绝好友申请
            /// 调用 acceptFriendApplication 同意好友申请且同意类型为 V2TIM_FRIEND_ACCEPT_AGREE 时
            /// 申请加别人好友被拒绝
            onFriendApplicationListDeleted: (userIDList) {},

            ///好友申请已读通知，如果调用 setFriendApplicationRead 设置好友申请列表已读，会收到这个回调（主要用于多端同步）
            onFriendApplicationListRead: () {
              print("好友申请列表已读");
              Provider.of<ImProvider>(GlobalContext.getContext(), listen: false)
                  .setUnFriendReadCount(0);
            },

            ///好友新增通知
            onFriendListAdded: (List<V2TimFriendInfo> users) {
              print("新增好友${users.toString()}");
            },

            ///好友删除通知，，两种情况会收到这个回调：
            ///
            /// 自己删除好友（单向和双向删除都会收到回调）
            /// 好友把自己删除（双向删除会收到）
            onFriendListDeleted: (List<String> userList) {
              print("好友删除${userList.toString()}");
            },
          ),
        );
  }

  ///创建群聊
  Future<String?> createGroup(String groupName, List<Map> memberList) async {
    String faceUrl =
        "https://sf3-ttcdn-tos.pstatp.com/img/user-avatar/e1a14e51c82e80068414b25a144a2413~300x300.image";

    ///群头像
    if (currentUserHead != null) {
      faceUrl = currentUserHead;
    }

    var _result = await TencentImSDKPlugin.v2TIMManager
        .getGroupManager()
        .createGroup(
            groupType: GroupCommonType.GROUP_WORK_TYPE,
            groupName: groupName,
            faceUrl: faceUrl,
            memberList: memberList);

    print("${_result.desc}--->${_result.data}-->${_result.code}");

    if (_result.code == 0) {
      return Future.value(_result.data);
    } else {
      return Future.value(null);
    }
  }

  ///初始化群聊监听
  void initGroupListener() {
    TencentImSDKPlugin.v2TIMManager.setGroupListener(
        listener: new V2TimGroupListener(
      onGroupCreated: (String groupId) {
        //群创建
        //print("创建群聊成功:$groupId");
        insertGroupMessageToLocalStorage(
            "创建群聊成功", GroupCommonType.SENDER_TIM_USER, groupId);
      },
      onMemberInvited: (String groupID, V2TimGroupMemberInfo opUser,
          List<V2TimGroupMemberInfo> memberList) {
        //邀请人进入群聊
        print("${opUser.nickName} 邀请了${memberList[0].nickName} 加入$groupID");
      },
      onMemberKicked: (String groupID, V2TimGroupMemberInfo opUser,
          List<V2TimGroupMemberInfo> memberList) {
        //T人
        memberList.forEach((element) {
          if (element.userID == getUserId()) {
            insertGroupMessageToLocalStorage("您被${opUser.nickName}移除了群聊",
                GroupCommonType.SENDER_TIM_USER, groupID);
          }
        });
      },
      onGroupDismissed: (String groupID, V2TimGroupMemberInfo opUser) {
        //群解散
        insertGroupMessageToLocalStorage("${opUser.nickName}解散了群聊",
            GroupCommonType.SENDER_TIM_USER, groupID);
      },
      onMemberLeave: (String groupID, V2TimGroupMemberInfo member) {
        //有成员离开
        //print("${member.nickName}退出了群聊  $groupID");
        if (member.userID == getUserId()) {
          insertGroupMessageToLocalStorage(
              "您已退出了群聊", GroupCommonType.SENDER_TIM_USER, groupID);
        }
      },
    ));
  }

  ///获取群成员
  void getGroupMember(String groupID, int filter) async {
    V2TimValueCallback<V2TimGroupMemberInfoResult> _result =
        await TencentImSDKPlugin.v2TIMManager.v2TIMGroupManager
            .getGroupMemberList(groupID: groupID, filter: filter, nextSeq: "0");

    if (_result.code == 0) {
      if (_result.data!.memberInfoList != null) {
        Provider.of<ImProvider>(GlobalContext.getContext(), listen: false)
            .setGroupMembers(_result.data!.memberInfoList!);
      }
    }
  }

  ///判断群成员的全县，只有群主才能移除人员
  Future<bool> checkMemberAuthor(String groupID, String userId) async {
    V2TimValueCallback<List<V2TimGroupMemberFullInfo>> _result =
        await TencentImSDKPlugin.v2TIMManager.v2TIMGroupManager
            .getGroupMembersInfo(groupID: groupID, memberList: [userId]);

    if (_result.code == 0) {
      int? role = _result.data?[0].role;
      if (role == GroupCommonType.V2TIM_GROUP_MEMBER_ROLE_OWNER) {
        return Future.value(true);
      } else {
        return Future.value(false);
      }
    } else {
      return Future.value(false);
    }
  }

  ///邀请人进群
  Future<bool> inviteUserToGroup(String groupID, List<String> userList) async {
    V2TimValueCallback<List<V2TimGroupMemberOperationResult>> _result =
        await TencentImSDKPlugin.v2TIMManager.v2TIMGroupManager
            .inviteUserToGroup(groupID: groupID, userList: userList);

    if (_result.code == 0) {
      return Future.value(true);
    } else {
      return Future.value(false);
    }
  }

  ///移除人员
  Future<bool> kickGroupMember(String groupId, List<String> memberList) async {
    V2TimCallback _result = await TencentImSDKPlugin
        .v2TIMManager.v2TIMGroupManager
        .kickGroupMember(groupID: groupId, memberList: memberList);

    return Future.value(_result.code == 0);
  }

  ///退出群聊
  Future<bool> quitGroup(String groupID) async {
    V2TimCallback callback =
        await TencentImSDKPlugin.v2TIMManager.quitGroup(groupID: groupID);

    print("--->退出群聊:${callback.code}--->${callback.desc}");
    if (callback.code == 0) {
      insertGroupMessageToLocalStorage(
          "您已退出了群聊", GroupCommonType.SENDER_TIM_USER, groupID);
    }

    return Future.value(callback.code == 0);
  }

  ///解散群聊
  Future<bool> dismissGroup(String groupID) async {
    V2TimCallback callback =
        await TencentImSDKPlugin.v2TIMManager.dismissGroup(groupID: groupID);

    return Future.value(callback.code == 0);
  }

  ///获取群资料
  Future<V2TimGroupInfo?> getGroupInfo(String groupID) async {
    V2TimValueCallback<List<V2TimGroupInfoResult>> _result =
        await TencentImSDKPlugin.v2TIMManager
            .getGroupManager()
            .getGroupsInfo(groupIDList: [groupID]);

    print("获取群资料${_result.code}");

    if (_result.code == 0) {
      if (_result.data != null && _result.data!.isNotEmpty) {
        return Future.value(_result.data![0].groupInfo);
      }
    }
    return Future.value(null);
  }

  ///检测是否加入了群  false 表示没有加入群聊，true 表示加入了这个群聊
  Future<bool> checkGroupState(String groupId) async {
    V2TimValueCallback<List<V2TimGroupInfo>> callback = await TencentImSDKPlugin
        .v2TIMManager
        .getGroupManager()
        .getJoinedGroupList();

    if (callback.code == 0) {
      bool? flag = callback.data
          ?.where((element) => element.groupID == groupId)
          .isNotEmpty;
      return Future.value(flag);
    } else {
      return Future.value(false);
    }
  }

  ///修改群名
  Future<bool> updateGroupName(String groupID, String groupName) async {
    //先获取到群信息
    V2TimGroupInfo? groupInfo = await getGroupInfo(groupID);

    if (groupInfo != null) {
      V2TimGroupInfo v2timGroupInfo = V2TimGroupInfo.fromJson({
        "groupID": groupID,
        "groupName": groupName,
        "groupType": groupInfo.groupType,
        "notification": groupInfo.notification,
        "introduction": groupInfo.introduction,
        "faceUrl": groupInfo.faceUrl,
        "isAllMuted": groupInfo.isAllMuted,
        "addOpt": groupInfo.groupAddOpt,
      });

      //修改群信息
      V2TimCallback callback = await TencentImSDKPlugin.v2TIMManager
          .getGroupManager()
          .setGroupInfo(info: v2timGroupInfo);

      return Future.value(callback.code == 0);
    } else {
      return Future.value(false);
    }
  }

  ///转让群
  void transferGroupOwner(String groupID, String userID) {
    TencentImSDKPlugin.v2TIMManager
        .getGroupManager()
        .transferGroupOwner(groupID: groupID, userID: userID)
        .then((value) => print("转让群:${value.code}"));
  }

  ///插入群聊一条消息
  void insertGroupMessageToLocalStorage(
      String data, String senderId, String groupID) async {
    V2TimValueCallback<V2TimMessage> _result = await TencentImSDKPlugin
        .v2TIMManager.v2TIMMessageManager
        .insertGroupMessageToLocalStorage(
            data: data, groupID: groupID, sender: senderId);
    if (_result.code == 0) {
      Provider.of<ImProvider>(GlobalContext.getContext(), listen: false)
          .addMessage(MessageCacheKey.getGroupKey(groupID), _result.data!);
    }
  }
}
